/****************************************************************************
	This file is part of Basqet.

	Basqet is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Basqet is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
    along with Basqet.  If not, see <http://www.gnu.org/licenses/>.

****************************************************************************/

#include "backupworker.h"
#include "settings.h"

#include "copyrecursiveworker.h"
#include "removerecursiveworker.h"

#include <QApplication>
#include <QDate>
#include <QTimer>

#include <QSettings>

#include <QStringList>

#include <QFileInfo>
#include <QDir>

#include <QtDebug>

BackupWorker::BackupWorker()
{
}

void BackupWorker::run()
{
	qDebug() << "Starting the backupthread";

	QTimer* timer = new QTimer();

	connect(timer, SIGNAL(timeout()), this, SLOT(manageBackup()));

	timer->start(60000);

	exec();


}


bool BackupWorker::manageBackup()
{
	bool bOk = true;
	QSettings settings;


	// Check if we are to make backups.
	if (settings.value(SETTING_DO_BACKUPS).toBool())
	{
		QString backupDate = QDate::currentDate().toString("yyyyMMdd");
		QFileInfo backupTo(QDir(settings.value(SETTING_BACKUP_ROOT).toString()),
						   backupDate);
		QFileInfo backupRoot(settings.value(SETTING_BACKUP_ROOT).toString());

		if (backupRoot.exists())
		{

			if (!backupTo.exists())
			{
				QFileInfo backupFrom(settings.value(SETTING_DATA_ROOT).toString());

				CopyRecursiveWorker copyWorker;

				copyWorker.copyRecursive(backupFrom, backupTo);

				clearOldBackups(backupRoot, settings.value(SETTING_NO_OF_BACKUPS).toInt());

			}

		}
		else
		{
			qDebug() << "Cannot locate target for backups, will try again later";
			bOk = false;
		}

	}

	return bOk;

}


void BackupWorker::clearOldBackups(QFileInfo backupTo, int noOfBackupsToKeep)
{
	QStringList existingBackups;

	QDir	backupDir(backupTo.filePath());
	QFileInfoList backups = backupDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot);

	foreach(QFileInfo entry, backups)
	{
		qDebug() << "Existing backup: " << entry.fileName();
		existingBackups.append(entry.fileName());

	}
	existingBackups.sort();

	qDebug() << "Existing entries: " << existingBackups;

	if (noOfBackupsToKeep < 3)
		noOfBackupsToKeep = 3;

    int backupsToRemove = existingBackups.size() - noOfBackupsToKeep;  // Can be less than zero

    if (backupsToRemove > 0)
    {

        // There are backups to remove.

        // We use the existingBackups as a list of backups to remove.
        // First wer must take out all backups that is to be kept.


        // Remove all elements from list but those to remove.
        while (existingBackups.size() > backupsToRemove)
        {
            existingBackups.takeLast();
        }

        qDebug() << "Backups to remove:" << existingBackups;

        RemoveRecursiveWorker removeWorker;
        foreach(QString entry, existingBackups)
        {
            QFileInfo backup(QDir(backupTo.filePath()), entry);
            qDebug() << "Remove backup:" << backup.filePath();

            removeWorker.removeRecursive(backup);

        }
    }



}


